package club.banyuan.hrms.servlet;

import club.banyuan.hrms.dao.PositionDao;
import club.banyuan.hrms.dao.impl.PositionDaoImpl;
import club.banyuan.hrms.domain.Department;
import club.banyuan.hrms.domain.Position;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PositionListServlet extends HttpServlet {
    PositionDao positionDao;

    @Autowired
    public PositionListServlet(PositionDao positionDao) {
        this.positionDao = positionDao;
    }

    public PositionDao getPositionDao() {
        return positionDao;
    }

    public void setPositionDao(PositionDao positionDao) {
        this.positionDao = positionDao;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        // 获取查询参数
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        Position position = new Position();
        position.setId((id != null) ? Integer.parseInt(id) : null);
        position.setName(name);
        position.setDescription(description);

        if (id != null) {
            positionDao.updatePosition(position);
        } else {
            positionDao.addPosition(position);
        }

        response.sendRedirect(request.getContextPath() + "/positionManage.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");

        List<Position> positions = positionDao.getPositions();

        // 按照接口要求返回数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", positions.size());
        resultMap.put("code", 0);
        resultMap.put("rows", positions);
        response.getWriter().println(JSONObject.toJSONString(resultMap));
    }
}
